<template>
    <rx-dialog @handOk="handleSubmit" @cancel="cancel">
        <a-modal v-model="visible" :z-index="30000" :title="i18n('form.testResult','测试结果')" @ok="hideModal">
            <a-textarea v-model="result" style="height:200px"></a-textarea>

            <template slot="footer">
                <a-button key="back" @click="hideModal">
                    {{$ti18('rxForm.closeBtn','关闭')}}
                </a-button>
            </template>
        </a-modal>

        <a-form-model ref="form" :model="mdl" :rules="rules">
            <a-form-model-item style="display: none">
                <a-input v-model="mdl.id"/>
                <a-input v-decorator="['mdl.appId',{initialValue:mdl.appId?mdl.appId:curApp.appId}]"/>
            </a-form-model-item>
            <a-row>
                <a-col :span="8">
                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.category','分类')" prop="treeId">
                        <rx-category-select v-if="isShowManageTree" :isAdmin="isManageToTree" cat-key="FORM" :isGrant="true" v-model="mdl.treeId"></rx-category-select>
                    </a-form-model-item>
                </a-col>
                <a-col :span="8" v-show="false">
                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.application','所属应用')"
                                       v-if="curApp.appName && curApp.appName !=''">
                        <a-input :disabled="true" v-model="curApp.appName"/>
                    </a-form-model-item>
                </a-col>

                <a-col :span="8">
                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.name','名称')" prop="name" >
                        <a-input @blur.native="getPinyinByName" :placeholder="i18n('form.name','名称','input')" v-model="mdl.name"/>
                    </a-form-model-item>
                </a-col>
                <a-col :span="8">
                    <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" :label="i18n('form.alias','别名')" prop="alias" class=" x-a-form-model-error">
                        <a-input :placeholder="i18n('form.alias','别名','input')" v-model="mdl.alias"/>
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="24">
                  <a-form-model-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.type','脚本类型')" prop="type">
                    <a-radio-group :placeholder="i18n('form.type','脚本类型','input')" v-model="mdl.type">
                      <a-radio value="java">java</a-radio>
                      <a-radio value="python">python</a-radio>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="24">
                    <a-form-model-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.parameterDefinition','参数定义')" prop="params">
                        <div class="table-operator">
                            <a-button @click="addParam" size="small">
                                {{i18n('button.newParameter','新增参数')}}
                            </a-button>
                            <a-button @click="addSubParam" size="small">
                                {{i18n('button.newSubparameter','新增子参数')}}
                            </a-button>
                            <a-button @click="removeParam" size="small">
                                {{i18n('button.deleteParameter','删除参数')}}
                            </a-button>
                            <a-button @click="upParam" size="small">
                                {{i18n('button.upward','向上')}}
                            </a-button>
                            <a-button @click="downParam" size="small">
                                {{i18n('button.down','向下')}}
                            </a-button>
                            <a-button @click="onDebug" size="small">
                                {{i18n('button.test','测试')}}
                            </a-button>
                        </div>
                        <rx-grid
                            ref="table"
                            :columns="columns"
                            :dataSource="dataSource"
                            :allowRowSelect="true"
                            :multiSelect="true"
                            :showPage="false"
                            :bordered="true"
                            style="height:180px;"
                        >
                          <span slot="paramName" slot-scope="{text,record,index,blur}">
                            <a-input v-model="record.paramName" @blur="blur(index,'paramName',text,record)"/>
                          </span>
                          <span slot="paramType" slot-scope="{text,record,index,blur}">
                            <a-select  v-model="record.paramType" :options="typeList" @blur="blur(index,'paramType',text,record)" @change="changeType(record)">
                            </a-select>
                          </span>
                          <span slot="paramDescp" slot-scope="{text,record,index,blur}">
                            <a-input v-model="record.paramDescp" @blur="blur(index,'paramDescp',text,record)"/>
                          </span>
                          <span slot="value" slot-scope="{text,record,index,blur}">
                            <a-input v-model="record.value" @blur="blur(index,'value',text,record)"/>
                          </span>
                        </rx-grid>
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="24">
                    <a-form-model-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="(mdl.type=='java'?'Groovy':'Python')+i18n('form.script','脚本')" prop="content">
                        <rx-monaco-editor ref="javaCode"
                                          language="java"
                                          style="height:200px;"
                                          v-model="mdl.content">
                            <template v-slot:monacoeditor>
                                <a-dropdown>
                                    <a-menu slot="overlay"  >
                                        <template v-for="item in ScriptInsertAry">
                                            <a-menu-item :key="item.clickEvent" @click="insertScript(item.script)" v-if="!item.children"> {{item.name}} </a-menu-item>

                                            <a-sub-menu :key="item.name"  v-if="item.children && item.children.length>0">
                                                <span slot="title">{{item.name}}</span>
                                                <a-menu-item :key="subItem.name"  v-for="subItem in item.children" @click="insertScript(subItem.script)">
                                                    {{subItem.name}}
                                                </a-menu-item>
                                            </a-sub-menu>


                                        </template>
                                    </a-menu>
                                    <a-button type="primary" style="margin-left: 8px" size="small">
                                        {{i18n('button.insertParams','插入参数')}}
                                        <a-icon type="down" /> </a-button>
                                </a-dropdown>
                                &nbsp;
                                <a-button icon="edit" @click="showScriptDialog()" size="small">
                                    {{i18n('button.quickScript','快速脚本')}}
                                </a-button>
                                &nbsp;
                                <a-button   @click="selectDataSource()" size="small">
                                    {{i18n('button.selectDS','选择数据源')}}
                                </a-button>
                            </template>
                        </rx-monaco-editor>
                        <span style="padding:2px;line-height: 18px;font-size:12px; ">
                            {{i18n('text','说明：上下文包括了变量为params的参数,其为Java中的java.utilMap类型,可在脚本中通过params["参数名"]获取参数,通过 也可通过params.containsKey("参数名")来判断参数是否存在。')}}
                        </span>
                    </a-form-model-item>
                </a-col>
            </a-row>
            <a-row>
                <a-col :span="24">
                    <a-form-model-item :labelCol="labelCol1" :wrapperCol="wrapperCol1" :label="i18n('form.description','描述')" prop="descp">
                        <a-textarea :placeholder="i18n('form.description','描述','input')" v-model="mdl.descp" :rows="2"/>
                    </a-form-model-item>
                </a-col>
            </a-row>
        </a-form-model>
    </rx-dialog>
</template>
<script>
import FormInvokeScriptApi from '@/api/form/core/formInvokeScript'
import {BaseFormModel, RxDialog, RxMonacoEditor, RxGrid, Util,Dialog,JsConstant} from "@lowcode/jpaas-common-lib";
import AppName from "@/assets/js/AppName.js";

export default {
    name: 'FormInvokeScriptEdit',
    mixins: [BaseFormModel,AppName],
    components: {
        RxDialog,
        RxMonacoEditor,
        RxGrid
    },
    computed: {
        table() {
            return this.$refs.table;
        }
    },

    data() {
        return {
            labelCol: { span:6 },
            wrapperCol: { span:18 },
            labelCol1: { span:2 },
            wrapperCol1: { span:19 },
            ScriptInsertAry:[] ,
            rules: {
                treeId: [{required: true, message: this.i18n('form.ClassificationID','分类ID','input'), trigger: 'change'}],
                name: [{required: true, message: this.i18n('form.name','名称','input'), trigger: 'change'}],
                alias: [
                    {required: true, message: this.i18n('form.alias','别名','input'), trigger: 'change'},
                    {pattern:/^[a-zA-Z][a-zA-Z0-9_-]*$/,message:this.i18n2('form.str','不能以数字开头,不能包含【_-】以外的特殊字符！','input')}
                ]
            },
            columns: [{
                title: this.i18n('form.paramName','参数名'),
                dataIndex: 'paramName',
                allowCellEdit: false,
                width: 200,
                scopedSlots: {customRender: 'paramName'}
                },
                {
                    title: this.i18n('form.paramType','参数类型'),
                    dataIndex: 'paramType',
                    allowCellEdit: true,
                    displayField: 'paramType_name',
                    width: 150,
                    scopedSlots: {customRender: 'paramType'}
                },
                {
                    title: this.i18n('form.description','描述'),
                    dataIndex: 'paramDescp',
                    allowCellEdit: false,
                    width: 260,
                    scopedSlots: {customRender: 'paramDescp'}
                },{
                    title: this.i18n('form.value','值'),
                    dataIndex: 'value',
                    allowCellEdit: false,
                    width: 200,
                    scopedSlots: {customRender: 'value'}
                }],

            dataSource: [],
            result: "",
            visible: false,

            rootParams:{
                name:this.i18n('button.parameter','插入上下文参数'),
                alias:`params`,
                script:`params`,
                children:[]
            },
            typeList:[{label:this.i18n('type.character','字符'),value:"string"},
                    {label:this.i18n('type.integer','整型'),value:"int"},
                    {label:this.i18n('type.long','长整形'),value:"long"},
                    {label:this.i18n('type.number','数字'),value:"double"},
                    {label:this.i18n('type.dateType','日期型'),value:"date"},
                    {label:this.i18n('type.boolean','布尔型'),value:"boolean"},
                    {label:this.i18n('type.objectType','对象型'),value:"obj"}]

        }
    },
    created() {
        this.isUserManager(this.$route.query.appId);
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "formInvokeScript", key);
        },
        i18n2(name,text,key){
            return this.$ti18(name,text,"formBoEntity",key);
        },
        insertScript(script){
            this.$refs.javaCode.insertContent(script);
        },
        changeType(record){
            let type=record.paramType;
            if(!type){
                record.paramType_name="";
                return ;
            }

            let ary=this.typeList.filter(item=>{
                return type==item.value;
            });
            record.paramType_name=ary[0].label;
        },
        onload_(values) {
            this.ScriptInsertAry.unshift(this.rootParams);
            if (values) {
                if (values.params) {
                    this.dataSource = JSON.parse(values.params);
                    //初始化参数
                    this.initParams();
                }
            }else{
              this.mdl = Object.assign({
                type:"java"
              });
            }
        },
        getPinyinByName(){
            let name=this.mdl.name
            if (!name){
                return;
            }
            if (this.mdl.alias){
                return;
            }
            this.getPinyin(name).then(res => {
                //去除不可见的特殊符号
                if(res){
                    res=res.replace(/\u200B/g,'');
                }
                this.$set(this.mdl,"alias",res)
            })
        },
        initParams(){
            let children=this.rootParams.children;
            children.length=0;
            for(let i=0;i<this.dataSource.length;i++){
                let param=this.dataSource[i];
                children.push({
                    name:param.paramDescp || param.paramName,
                    script:'params.' + param.paramName
                })
            }
        },
        get(id) {
            return FormInvokeScriptApi.get(id);
        },
        save(values) {
            var rows = this.table.getData();

            /*rows.forEach(item => {
                item.value = "";
            })*/
            values.params = JSON.stringify(rows);
            if (!values.pkId && this.curApp.appId) {
                values.appId = this.curApp.appId;
            }
            return FormInvokeScriptApi.save(values);
        },
        addParam() {
            this.table.addRow();
        },
        addSubParam() {
            var row = this.table.getSelectedRow();
            if (!row) {
                this.$message.warning(this.i18n('content.isLine','"请选择一行!'));
                return;
            }
            if (row.paramType != 'obj') {
                this.$message.warning(this.i18n('content.isObject','"请选择类型为对象型的参数!'));
                return;
            }
            var ary;
            if (row.children) {
                ary = row.children;
            } else {
                ary = row.children = [];
            }
            this.table.addItem(ary, {parentId: row['idx_']});
            this.table.$forceUpdate();
        },
        removeParam() {
            this.table.removeRows();
        },
        upParam() {
            this.table.moveUp();
        },
        downParam() {
            this.table.moveDown();
        },
        onDebug() {
            let content=this.mdl.content ||"";
            content=content.trim();
            if(!content){
                this.$message.warn(this.i18n('content.isScript','请填写脚本!'));
                return;
            }

            var rows = this.table.getData();
            var json = {
                script: content,
                params: rows
            }

            FormInvokeScriptApi.test(json).then(res => {
                if(res.success) {
                    this.visible = true;
                    let rtn= res.data;
                    if(typeof rtn =="number"){
                        rtn=rtn +"";
                    }
                    if(typeof rtn =="object"){
                        rtn=JSON.stringify(rtn);
                    }
                    this.result = rtn;
                }
            })
        },
        hideModal() {
            this.visible = false;
        },
        showScriptDialog(){
            let self=this;
            let config={curVm:this};
            Dialog.openScriptDialog(config,function (script){
                self.$refs.javaCode.insertContent(script);
            })

        },
        selectDataSource(){
            Dialog.openDataSourceDialog({
                curVm: this, widthHeight: ['900px', '500px'],
                data:{appName:this.serviceName}
            }, function (self, data) {
                self.insertScript('"'+data.alias+'"');
            })
        }

    },
    watch:{
        dataSource:{
            handler(val){
                this.initParams();
            },
            deep:true
        }
    }
}
</script>
